<template>
  <view class="container">
    <!-- 合并后的顶部导航栏 -->
    <view class="custom-nav-bar">
      <view class="nav-left" @click="goBack">
        <FeatherIcon name="chevron-left" size="24" color="#333" />
      </view>
      <view class="nav-title">我的消息</view>
      <view class="nav-right" @click="handleReadAll(true)">
        <FeatherIcon name="check-circle" size="24" color="#333" />
      </view>
    </view>

    <!-- 固定在顶部的筛选栏 -->
    <scroll-view class="filter-tabs" scroll-x="true" show-scrollbar="false">
      <view class="tabs-container">
        <view
          class="tab-item"
          v-for="(item, index) in tabList"
          :key="index"
          :class="{ active: currentTab === item.type }"
          @click="switchTab(item.type)"
        >
          {{ item.name }}
          <text v-if="item.unread > 0" class="unread-badge">{{
            item.unread
          }}</text>
        </view>
      </view>
    </scroll-view>

    <!-- 内容区域 -->
    <swiper
      class="content-container"
      :current="currentTabIndex"
      @change="handleSwiperChange"
    >
      <swiper-item v-for="(tab, index) in tabList" :key="index">
        <scroll-view
          scroll-y="true"
          class="notification-scroll"
          @scrolltolower="loadMore"
          refresher-enabled="true"
          :refresher-triggered="refreshing"
          @refresherrefresh="onRefresh"
        >
          <!-- 根据当前类型加载对应的组件 -->
          <component
            :is="getComponentByType(tab.type)"
            :notifications="notifications"
            :loading="loading"
            @notification-click="handleNotificationClick"
          ></component>

          <!-- 加载状态 -->
          <view class="loading-state" v-if="loading">
            <view class="loading-icon"></view>
            <text class="loading-text">加载中...</text>
          </view>

          <!-- 加载更多 -->
          <view class="load-more" v-if="notifications.length > 0 && hasMore">
            <text
              class="load-more-text"
              @click="loadMore"
              :class="{ disabled: loading }"
            >
              {{ loading ? "加载中..." : "加载更多" }}
            </text>
          </view>

          <!-- 已经到底了提示 -->
          <view class="no-more" v-if="notifications.length > 0 && !hasMore">
            <text class="no-more-text">已经到底了~</text>
          </view>
        </scroll-view>
      </swiper-item>
    </swiper>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch, shallowRef } from "vue";
import {
  formatDate,
  timeAgo,
  showLoading,
  hideLoading,
  showError,
  showSuccess,
  showConfirm,
} from "@/utils/common.js";
import api from "@/api";
import { isLoggedIn } from "@/api";
import FeatherIcon from "@/components/FeatherIcon.vue";

// 导入通知组件
import PointNotification from "@/components/notification/PointNotification.vue";
import CommentedNotification from "@/components/notification/CommentedNotification.vue";
import ReplyNotification from "@/components/notification/ReplyNotification.vue";
import AtNotification from "@/components/notification/AtNotification.vue";
import FollowingNotification from "@/components/notification/FollowingNotification.vue";

// 通知类型列表（移除了系统通知类型）
const tabList = reactive([
  { name: "积分", type: "point", unread: 0 },
  { name: "评论", type: "commented", unread: 0 },
  { name: "回复", type: "reply", unread: 0 },
  { name: "提及我的", type: "at", unread: 0 },
  { name: "关注", type: "following", unread: 0 },
]);

// 当前选中的通知类型
const currentTab = ref("point");
// 通知列表数据
const notifications = ref([]);
// 页码
const page = ref(1);
// 是否还有更多数据
const hasMore = ref(true);
// 是否正在加载
const loading = ref(false);
// 是否正在刷新
const refreshing = ref(false);

// 当前选中的标签索引
const currentTabIndex = computed(() => {
  return tabList.findIndex((item) => item.type === currentTab.value);
});

// 根据类型获取对应的组件
const getComponentByType = (type) => {
  switch (type) {
    case "point":
      return PointNotification;
    case "commented":
      return CommentedNotification;
    case "reply":
      return ReplyNotification;
    case "at":
      return AtNotification;
    case "following":
      return FollowingNotification;
    default:
      return PointNotification;
  }
};

// 获取未读消息数量
const getUnreadCount = async () => {
  try {
    const res = await api.notification.getUnreadCount();
    if (res.code === 0) {
      // 更新每个标签的未读数量
      tabList.forEach((tab) => {
        switch (tab.type) {
          case "reply":
            tab.unread = res.unreadReplyNotificationCnt || 0;
            break;
          case "point":
            tab.unread = res.unreadPointNotificationCnt || 0;
            break;
          case "at":
            tab.unread = res.unreadAtNotificationCnt || 0;
            break;
          case "following":
            tab.unread = res.unreadFollowingNotificationCnt || 0;
            break;
          case "commented":
            tab.unread = res.unreadCommentedNotificationCnt || 0;
            break;
          default:
            tab.unread = 0;
        }
      });
    }
  } catch (error) {
    console.error("获取未读消息数量失败", error);
  }
};

// 下拉刷新
const onRefresh = async () => {
  refreshing.value = true;
  try {
    // 重置页码
    page.value = 1;
    // 重新加载通知列表
    await loadNotifications();
    // 重新获取未读消息数量
    await getUnreadCount();
  } catch (error) {
    console.error("刷新失败", error);
  } finally {
    refreshing.value = false;
  }
};

// 处理滑动切换
const handleSwiperChange = (e) => {
  const index = e.detail.current;
  currentTab.value = tabList[index].type;
};

// 切换通知类型
const switchTab = (type) => {
  if (currentTab.value === type) return;

  currentTab.value = type;
  page.value = 1;
  hasMore.value = true;
  notifications.value = [];

  loadNotifications();
};

// 加载通知列表
const loadNotifications = async () => {
  if (!isLoggedIn()) {
    uni.navigateTo({
      url: "/pages/login/login",
    });
    return;
  }

  if (loading.value) return;

  try {
    loading.value = true;

    const res = await api.notification.getNotifications(
      currentTab.value,
      page.value
    );

    if (res.code === 0) {
      let newData = res.data || [];

      if (page.value === 1) {
        notifications.value = newData;
      } else {
        notifications.value = [...notifications.value, ...newData];
      }

      // 判断是否还有更多数据
      hasMore.value = newData.length >= 20;
    } else {
      showError(res.msg || "获取通知列表失败");
    }
  } catch (error) {
    console.error("加载通知失败", error);
  } finally {
    loading.value = false;
  }
};

// 加载更多通知
const loadMore = () => {
  if (loading.value || !hasMore.value) return;

  page.value++;
  loadNotifications();
};

// 处理通知点击
const handleNotificationClick = async (routeInfo) => {
  console.log("通知点击", routeInfo);

  if (!routeInfo) {
    showError("无效的通知");
    return;
  }

  try {
    // 如果有需要标记已读的ID
    // if (routeInfo.readId) {
    //   await markAsReadAndUpdate(routeInfo.readId);
    // }

    // 根据标准化的路由信息进行导航
    switch (routeInfo.type) {
      case "article":
        // 跳转到文章详情
        if (routeInfo.params && routeInfo.params.id) {
          uni.navigateTo({
            url: `/pages/article/detail?id=${routeInfo.params.id}`,
          });
        } else {
          throw new Error("缺少文章ID");
        }
        break;

      case "webview":
        // 跳转到网页
        if (routeInfo.params && routeInfo.params.url) {
          uni.navigateTo({
            url: `/pages/webview/webview?url=${encodeURIComponent(
              routeInfo.params.url
            )}`,
          });
        } else {
          throw new Error("缺少网页URL");
        }
        break;

      case "chat":
        // 跳转到聊天室
        uni.switchTab({
          url: "/pages/chat/chat",
        });
        break;

      case "unknown":
      default:
        // 无法确定跳转目标，提示用户
        console.log("无法确定跳转目标", routeInfo);
        //showError("无法处理该类型的通知");
        break;
    }
  } catch (err) {
    console.error("处理通知点击错误", err, routeInfo);
    showError(err.message || "处理通知失败");
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 标记为已读并更新UI
const markAsReadAndUpdate = async (notificationId) => {
  try {
    const res = await api.notification.markAsRead(notificationId);
    if (res.code === 0) {
      // 更新通知状态 - 使用数组方法触发响应式更新
      const index = notifications.value.findIndex(
        (n) => n.oId === notificationId
      );
      if (index !== -1) {
        const updatedNotification = {
          ...notifications.value[index],
          hasRead: true,
        };
        notifications.value.splice(index, 1, updatedNotification);

        // 更新当前标签的未读数量
        const currentTabObj = tabList.find(
          (tab) => tab.type === currentTab.value
        );
        if (currentTabObj && currentTabObj.unread > 0) {
          currentTabObj.unread--;
        }
      }
      // 更新未读消息数量
      await getUnreadCount();
    }
  } catch (error) {
    console.error("标记通知已读失败", error);
  }
};

// 监听当前选中的通知类型变化
watch(currentTab, () => {
  page.value = 1;
  hasMore.value = true;
  notifications.value = [];

  loadNotifications();
});

// 一键已读所有通知
const handleReadAll = async (readAll = false) => {
  // 确认提示信息
  const message = readAll
    ? "确定要将所有消息标记为已读吗？"
    : `确定要将所有"${
        tabList.find((item) => item.type === currentTab.value)?.name || ""
      }"类型的消息标记为已读吗？`;

  // 显示确认框
  const confirmed = await showConfirm(message);
  if (!confirmed) return;

  showLoading("处理中...");
  try {
    let res;

    // 根据参数选择调用不同的API
    if (readAll) {
      // 标记所有通知为已读
      res = await api.notification.readAllNotifications();
    } else {
      // 标记当前类型的通知为已读
      res = await api.notification.readNotifications(currentTab.value);
    }

    if (res.code === 0) {
      showSuccess("已全部标记为已读");

      // 更新所有通知为已读状态
      notifications.value = notifications.value.map((item) => ({
        ...item,
        hasRead: true,
      }));

      // 如果是全部已读，直接清零所有标签的未读数量
      if (readAll) {
        tabList.forEach((tab) => {
          tab.unread = 0;
        });
      } else {
        // 只清零当前标签的未读数量
        const currentTabObj = tabList.find(
          (tab) => tab.type === currentTab.value
        );
        if (currentTabObj) {
          currentTabObj.unread = 0;
        }
      }

      // 更新未读消息数量
      await getUnreadCount();
    } else {
      showError(res.msg || "操作失败");
    }
  } catch (error) {
    console.error("标记已读失败", error);
    showError("操作失败，请稍后重试");
  } finally {
    hideLoading();
  }
};

// 检查并切换到有未读消息的标签
const switchToUnreadTab = () => {
  // 首先查找是否有未读消息的标签
  const unreadTab = tabList.find((tab) => tab.unread > 0);

  // 如果找到有未读消息的标签，切换到该标签
  if (unreadTab) {
    switchTab(unreadTab.type);
  }
};

onMounted(() => {
  if (isLoggedIn()) {
    // 先获取未读消息数量
    getUnreadCount().then(() => {
      // 初始化加载通知列表
      loadNotifications();

      // 检查是否有其他标签有未读消息，如果有则切换
      setTimeout(() => {
        // 如果默认标签没有未读消息，但其他标签有，则切换到有未读消息的标签
        if (tabList[0].unread === 0) {
          switchToUnreadTab();
        }
      }, 500); // 稍微延迟，确保未读数已加载
    });
  } else {
    uni.navigateTo({
      url: "/pages/login/login",
    });
  }
});
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-top: 180rpx;
}

.custom-nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  display: flex;
  align-items: center;
  padding: 20rpx;
  padding-top: 50rpx;
  padding-bottom: 0;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

  .nav-left,
  .nav-right {
    width: 80rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    .nav-icon {
      width: 40rpx;
      height: 40rpx;
    }
  }

  .nav-title {
    flex: 1;
    text-align: center;
    font-size: 32rpx;
    font-weight: bold;
  }
}

.filter-tabs {
  position: fixed;
  top: 130rpx;
  left: 0;
  right: 0;
  z-index: 99;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  white-space: nowrap;

  .tabs-container {
    display: inline-flex;
    padding: 0 20rpx;
  }

  .tab-item {
    display: inline-block;
    height: 80rpx;
    line-height: 80rpx;
    padding: 0 30rpx;
    text-align: center;
    font-size: 28rpx;
    color: #666;
    position: relative;

    &.active {
      color: #ff9800;
      font-weight: bold;
    }

    .unread-badge {
      position: absolute;
      top: 10rpx;
      right: 10rpx;
      min-width: 30rpx;
      height: 30rpx;
      line-height: 30rpx;
      padding: 0 6rpx;
      text-align: center;
      background-color: #ff4d4f;
      color: #fff;
      border-radius: 15rpx;
      font-size: 20rpx;
      transform: scale(0.8);
    }
  }
}

.content-container {
  height: calc(100vh - 210rpx);
  margin-top: 50rpx;
}

.notification-scroll {
  height: 100%;
  box-sizing: border-box;
  padding: 20rpx;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 0;

  .loading-icon {
    width: 60rpx;
    height: 60rpx;
    border: 4rpx solid #f0f0f0;
    border-top: 4rpx solid #ff9800;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 30rpx;
  }

  .loading-text {
    font-size: 28rpx;
    color: #999;
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
}

.load-more {
  text-align: center;
  padding: 30rpx 0;

  .load-more-text {
    font-size: 28rpx;
    color: #007aff;

    &.disabled {
      color: #ccc;
    }
  }
}

.no-more {
  text-align: center;
  padding: 30rpx 0;

  .no-more-text {
    font-size: 28rpx;
    color: #999;
  }
}
</style>
